package com.i2bt.app.main.model;

import com.i2bt.common.AndroidRestContract;
import com.i2bt.common.Contract;
import com.i2bt.common.UserConfig;

import com.i2bt.app.main.MainActivity;
import com.i2bt.bean.FriendBean;
import com.i2bt.util.HttpUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * Title : 心跳处理线程类
 * 
 * Description : 每隔固定时间发心跳给服务器获取信息的接收
 * 
 * CreatedTime : 2014-8-19
 * 
 * @author wuliao & kakaxi & yi
 * 
 * @version 1.0
 * 
 */

public class HeartBeatHandle extends Thread {

	private MainActivity activity;

	private boolean isHeartBeatRun;

	private JSONObject jsonParam;

	public HeartBeatHandle(MainActivity activity) {
		this.activity = activity;
		isHeartBeatRun = true;
	}

	/**
	 * 打包心跳所需的json
	 * 
	 * @throws JSONException
	 */
	private void wrapHeartBeatJson() throws JSONException {
		jsonParam = new JSONObject();

		jsonParam
				.put(AndroidRestContract.REQUEST_ID, System.currentTimeMillis())
				.put(AndroidRestContract.ACTION, AndroidRestContract.HEART_BEAT)
				.put(AndroidRestContract.TOKEN, UserConfig.token)
				.put(AndroidRestContract.USER_ID, UserConfig.userId)
				.put(AndroidRestContract.HOMEBOX_ID, UserConfig.homeboxId);
	}

	/**
	 * 开启心跳
	 */
	@Override
	public void run() {
		super.run();

		while (isHeartBeatRun) {
			try {

				if (!UserConfig.token.trim().equals("")) {
					//包装心跳参数
					wrapHeartBeatJson();
					
					String responseJson = HttpUtil.newPostAndResponse(
							AndroidRestContract.REST_MESSAGE,
							jsonParam.toString());

					if (responseJson != null) {
						System.out.println("心跳 : " + responseJson);
						logicToUnwrap(true, responseJson);

					}
					System.out.println("心跳进行中..");
				}

			} catch (IOException e) {
				e.printStackTrace();
				System.out.println("心跳连接超时!");
			} catch (JSONException e) {
				e.printStackTrace();
				System.out.println("心跳json处理有误");
			}

			try {
				Thread.sleep(Contract.HEART_BEAT_TIME);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}

	}

	/**
	 * 关闭心跳
	 */
	public void close() {
		isHeartBeatRun = false;
	}

	protected void logicToUnwrap(boolean isSuc, String result)
			throws JSONException {
		
		System.out.println(result);
		
		if (isSuc) {
			JSONObject jsonParamResult = new JSONObject(result);

			if (jsonParamResult.getBoolean(AndroidRestContract.SUCCEED)) {
				
				List<FriendBean> friendMessageList = new ArrayList<FriendBean>();
				JSONArray friendMessageArray = jsonParamResult
						.getJSONArray(AndroidRestContract.FRIEND_MESSAGE);
				for (int i = 0; i < friendMessageArray.length(); i++) {
					friendMessageList.add(wrapToFriendBean(friendMessageArray
							.getJSONObject(i)));
				}
				
				//调用活动把好友发来的信息弹出到信息栏中
				activity.notifyMessage(friendMessageList);

			} else {
				System.out.println(jsonParamResult.getString(
						 AndroidRestContract.MESSAGE));
			}

		} else {
			System.out.println(result);
		}
	}

	/**
	 * 打包成好友bean
	 * 
	 * @return
	 * @throws JSONException
	 */
	public FriendBean wrapToFriendBean(JSONObject jsonObject)
			throws JSONException {
		FriendBean friendBean = new FriendBean();
		friendBean.setReceiver(jsonObject
				.getString(AndroidRestContract.FRIEND_MESSAGE_RECEIVER));
		friendBean.setSender(jsonObject
				.getString(AndroidRestContract.FRIEND_MESSAGE_SENDER));
		friendBean.setContent(jsonObject
				.getString(AndroidRestContract.FRIEND_MESSAGE_CONTENT));
		friendBean.setDate(jsonObject
				.getString(AndroidRestContract.FRIEND_MESSAGE_DATE));
		friendBean.setFlag(jsonObject
				.getInt(AndroidRestContract.FRIEND_MESSAGE_FLAG));
		return friendBean;
	}

}
